<?php
/**
 * ============================================================================
 * Copyright (c) 2015-2018 贵州大师兄信息技术有限公司 All rights reserved.
 * siteַ: http://www.dsxcms.com
 * ============================================================================
 * @author:     David Song<songdewei@163.com>
 * @version:    v1.0.0
 * ---------------------------------------------
 * Date: 2018/9/14
 * Time: 上午9:17
 */

namespace App\Library\User;


use App\Library\AuthenticatedUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

trait AddressTrait
{
    use AuthenticatedUser;
    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        $address = $request->post('address');
        $address_id = $request->post('address_id');

        if (isset($address['isdefault'])) {
            $this->user()->addresses()->update(['isdefault'=>0]);
        }

        if ($address_id) {
            $this->user()->addresses()->where('address_id', $address_id)->update($address);
            $address = $this->user()->addresses()->where('address_id', $address_id)->first();
        }else {
            $address = $this->user()->addresses()->create($address);
        }
        return ajaxReturn(['address'=>$address]);
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function setDefault(Request $request){
        $address_id = intval($request->input('address_id'));
        $this->user()->addresses()->update(['isdefault'=>0]);
        $this->user()->addresses()->where('address_id', $address_id)->update(['isdefault'=>1]);
        return ajaxReturn();
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delete(Request $request){
        $address_id = intval($request->input('address_id'));
        $this->user()->addresses()->where('address_id', $address_id)->delete();
        return ajaxReturn();
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAddress(Request $request)
    {
        $address_id = $request->get('address_id');
        $address = $this->user()->addresses()->where('address_id', $address_id)->first();
        return ajaxReturn(['address'=>$address]);
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAddressList(Request $request)
    {
        $items = $this->user()->addresses()->orderByDesc('isdefault')->get();
        return ajaxReturn(['items'=>$items]);
    }
}
